package cn.javass.dp.composite.example3;


import java.util.ArrayList;
import java.util.List;

/**
 * 组合对象
 */
public class Composite extends Compoment{

    /**
     * 用来存储组合对象中包含的子组件对象
     */
    private List<Compoment> childCompoments = null;

    private String name = "";

    public Composite(String name) {
        this.name = name;
    }

    @Override
    public void printStruct(String preName) {
        System.out.println(preName + "+" +this.name);
        //用于区分 composite 或者 leaf
        if (this.childCompoments != null) {
            preName +=  " ";
            for (Compoment childCompoment : childCompoments) {
                childCompoment.printStruct(preName);
            }
        }
    }

    @Override
    public void addChild(Compoment child) {
        //延时初始化
        if (childCompoments == null) {
            childCompoments = new ArrayList<>();
        }
        childCompoments.add(child);
    }
    @Override
    public void removeChild(Compoment child) {
        if (childCompoments != null) {
            childCompoments.remove(child);
        }
    }

    @Override
    public Compoment getChildren(int index) {
        if (childCompoments != null) {
            if (index > 0 && index < childCompoments.size()) {
                return childCompoments.get(index);
            }
        }
        return null;
    }
}
